package live.ifox.stage;

import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.inputmethod.EditorInfo;
import android.webkit.WebView;
import android.widget.EditText;

import live.ifox.factory.Url;

public class BrowserActivity extends AppCompatActivity {
    EditText in_url;
    WebView webView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_browser);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setTitle(R.string.browser);
        }

        in_url = findViewById(R.id.url);
        in_url.setHint("输入关键词或是网址");
        webView = findViewById(R.id.webView);
        in_url.setOnEditorActionListener(
                //当actionId == XX_GO 或者 XX_DONE时都触发
                //或者event.getKeyCode == ENTER 且 event.getAction == ACTION_DOWN时也触发
                //注意，这是一定要判断event != null。因为在某些输入法上会返回null。
                (v, actionId, event) -> {
                    if (actionId == EditorInfo.IME_ACTION_SEARCH ||
                            (event != null && KeyEvent.KEYCODE_ENTER == event.getKeyCode())) {
                        String kw = in_url.getText().toString();
                        if (kw.isEmpty())
                            return true;  //true，保留软键盘; false，隐藏软键盘

                        webView.loadUrl(Url.Prefix_Baidu + kw);
                    }
                    return false;
                }
        );
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}
